import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getMusicList, searchMusic } from '@/api/music'
import { ElMessage } from 'element-plus'

export const useMusicStore = defineStore('music', () => {
  // 所有音乐列表
  const allMusic = ref([])
  
  // 喜欢的音乐列表
  const likedMusic = ref([])
  
  // 搜索结果
  const searchResults = ref([])
  
  // 加载状态
  const loading = ref(false)
  
  // 获取所有音乐列表
  async function fetchAllMusic() {
    loading.value = true
    try {
      const response = await getMusicList()
      if (response.status === 0) {
        allMusic.value = response.data
        updateLikedMusic()
        return response.data
      } else {
        ElMessage.error(response.message)
        return []
      }
    } catch (error) {
      console.error('获取音乐列表失败:', error)
      return []
    } finally {
      loading.value = false
    }
  }
  
  // 更新喜欢的音乐列表
  function updateLikedMusic() {
    likedMusic.value = allMusic.value.filter(song => song.isFavorite === 1)
  }
  
  // 搜索音乐
  async function searchMusicList(keyword) {
    if (!keyword) {
      searchResults.value = []
      return []
    }
    
    loading.value = true
    try {
      const response = await searchMusic(keyword)
      if (response.status === 0) {
        searchResults.value = response.data
        return response.data
      } else {
        ElMessage.error(response.message)
        searchResults.value = []
        return []
      }
    } catch (error) {
      console.error('搜索失败:', error)
      searchResults.value = []
      return []
    } finally {
      loading.value = false
    }
  }
  
  // 更新歌曲喜欢状态
  function updateSongLikeStatus(songId, isLiked) {
    if (!songId) return; // 添加防御性检查
    
    try {
      // 更新所有相关列表中的状态
      const updateList = (list) => {
        if (!list || !Array.isArray(list)) return; // 添加防御性检查
        
        const song = list.find(s => s && s.id === songId)
        if (song) {
          song.isFavorite = isLiked ? 1 : 0
        }
      }
      
      updateList(allMusic.value)
      updateList(searchResults.value)
      
      // 更新喜欢列表
      updateLikedMusic()
    } catch (error) {
      console.error('更新歌曲喜欢状态时出错:', error)
      // 捕获并记录错误，但不抛出，避免影响主流程
    }
  }
  
  return {
    allMusic,
    likedMusic,
    searchResults,
    loading,
    fetchAllMusic,
    searchMusicList,
    updateLikedMusic,
    updateSongLikeStatus
  }
}) 